package com.patrol.logisticsmanage.ui.appear;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.patrol.logisticsmanage.R;
import com.patrol.logisticsmanage.common.LoadingProgressDialog;
import com.patrol.logisticsmanage.net.AppConfig;
import com.patrol.logisticsmanage.net.BaseObserver;
import com.patrol.logisticsmanage.net.BaseReponse;
import com.patrol.logisticsmanage.net.BaseRequest;
import com.patrol.logisticsmanage.ui.appear.model.Floor;
import com.patrol.logisticsmanage.ui.appear.model.SubCamp_Floor;
import com.patrol.logisticsmanage.ui.appear.model.SubmitInfo;
import com.patrol.logisticsmanage.ui.base.BaseActivity;
import com.patrol.logisticsmanage.ui.base.ImagePreviewUtils;
import com.patrol.logisticsmanage.ui.base.PickerDialog;
import com.patrol.logisticsmanage.ui.canteen.utils.GsonUtil;
import com.patrol.logisticsmanage.ui.canteen.utils.LogUtils;
import com.patrol.logisticsmanage.ui.canteen.utils.ToastUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhaoss.weixinrecorded.activity.RecordedActivity;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.dialog.OnPickerChooseListener;
import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.OptionPicker;
import org.jaaksi.pickerview.picker.TimePicker;
import org.jaaksi.pickerview.util.Util;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.RxGalleryFinalApi;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultDisposable;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@Route(path = "/app/AppearActivity")
public class AppearActivity extends BaseActivity implements OptionPicker.OnOptionSelectListener {

    ImageAdapter adapter;
    List<ImageInfo> imageInfos;
    boolean isCompleteUpload = false;
    boolean isUploading = false;
    int currentPosition = 0;
    @BindView(R.id.img_camera)
    ImageView imgCamera;
    @BindView(R.id.img_album)
    ImageView imgAlbum;

    List<MediaBean> mediaBeans = new ArrayList<>();
    @BindView(R.id.tv_time_space)
    TextView tvTimeSpace;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.et_floor)
    EditText etFloor;
    @BindView(R.id.et_roomNo)
    EditText etRoomNo;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.grid_exp)
    ExpandableGridView gridExp;

    @BindView(R.id.tv_submit)
    TextView tvSubmit;


    private TimePicker mTimePicker1, mTimePicker2;
    public final DateFormat sSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public final DateFormat sSimpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private int mCurrYear;

    int type1 = 0;
    Date date1 = new Date(), date2 = new Date();
    int type2 = 0;

    //地址选择器
    private OptionPicker mPicker;
    DefaultCenterDecoration decoration;

    private List<SubCamp_Floor> subCampList;
    SubCamp_Floor selectFloor;
    Floor floor;

    LoadingProgressDialog loadingProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appear);
        ButterKnife.bind(this);
        subCampList = new ArrayList<>();
        initAddressPickerView();
        initViews();

        adapter = new ImageAdapter(imageInfos, this, new ImageAdapter.OnItemDeleteClick() {
            @Override
            public void onItemDeleteClick(int position) {
                imageInfos.remove(position);
                adapter.notifyDataSetChanged();
            }
        }, new ImageAdapter.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                ImagePreviewUtils.goToPreview(imageInfos, position, AppearActivity.this);
            }
        });
        gridExp.setAdapter(adapter);

        loadingProgressDialog = new LoadingProgressDialog(this);
    }

    private void initViews() {
        imageInfos = new ArrayList();

        etName.setText(AppConfig.getString("realname"));
        etPhone.setText(AppConfig.getString("phone"));

        Calendar calendar = Calendar.getInstance();
        mCurrYear = calendar.get(Calendar.YEAR);

        type1 = type1 | TimePicker.TYPE_MONTH | TimePicker.TYPE_DAY | TimePicker.TYPE_HOUR | TimePicker.TYPE_MINUTE;
        type2 = type2 | TimePicker.TYPE_HOUR | TimePicker.TYPE_MINUTE;

        mTimePicker1 = new TimePicker.Builder(this, type1, new TimePicker.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(TimePicker picker, Date date) {
                date1 = date;
                mTimePicker2 = new TimePicker.Builder(AppearActivity.this, type1, new TimePicker.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(TimePicker picker, Date date) {
                        date2 = date;
                        tvTimeSpace.setText(sSimpleDateFormat.format(date1) + "~" + sSimpleDateFormat2.format(date2));
                    }
                }).setTimeMinuteOffset(10)
                        .setInterceptor(new BasePicker.Interceptor() {
                            @Override
                            public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                                pickerView.setCenterDecoration(decoration);
                                pickerView.setVisibleItemCount(3);
                                pickerView.setColor(Color.parseColor("#199475"), Color.parseColor("#444444"));
                            }
                        })
                        .setRangDate(date1.getTime(), date1.getTime() + 7200000)
                        .setSelectedDate(date1.getTime())
                        .create();
                mTimePicker2.show();
            }
        })
                // 设置时间区间
                .setRangDate(System.currentTimeMillis(), 1893563460000L)
                //.setContainsStarDate(true)
                .setTimeMinuteOffset(10)
                //.setSelectedDate(1526449500000L).setTimeMinuteOffset(10)
                // 设置选中时间
                .setSelectedDate(System.currentTimeMillis())
                // 设置pickerview样式
                .setInterceptor(new BasePicker.Interceptor() {
                    @Override
                    public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                        pickerView.setVisibleItemCount(3);
                        pickerView.setCenterDecoration(decoration);
                        pickerView.setColor(Color.parseColor("#199475"), Color.parseColor("#444444"));
                        // 将年月设置为循环的
                        int type = (int) pickerView.getTag();
                        if (type == TimePicker.TYPE_YEAR || type == TimePicker.TYPE_MONTH) {
                            pickerView.setIsCirculation(true);
                        }
                    }
                })
                // 设置 Formatter
                .setFormatter(new TimePicker.DefaultFormatter() {
                    // 自定义Formatter显示去年，今年，明年
                    @Override
                    public CharSequence format(TimePicker picker, int type, int position, long num) {
                        if (type == TimePicker.TYPE_YEAR) {
                            long offset = num - mCurrYear;
                            if (offset == -1) return "去年";
                            if (offset == 0) return "今年";
                            if (offset == 1) return "明年";
                            return num + "年";
                        } else if (type == TimePicker.TYPE_MONTH) {
                            return String.format("%d月", num);
                        }

                        return super.format(picker, type, position, num);
                    }
                }).create();
    }

    List<String> images = new ArrayList<>();

    private void uploadImage(){
        loadingProgressDialog.show();
        isUploading = true;
        ImageInfo img = imageInfos.get(currentPosition);
        File file = new File(img.getImageUrl());
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表單類型
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        builder.addFormDataPart("file", file.getName(), photoRequestBody);
        List<MultipartBody.Part> parts = builder.build().parts();


        BaseRequest.getInstance().getApiServise().upload(parts.get(0))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(mContext) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        loadingProgressDialog.hide();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        LogUtils.e("******" + baseReponse);
                        images.add(baseReponse.getMessage());
                        if (currentPosition!=imageInfos.size()-1){
                            isCompleteUpload = false;
                            currentPosition = currentPosition+1;
                            uploadImage();
                        }else {
                            isUploading = false;
                            isCompleteUpload = true;
                        }
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {

                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {

                    }
                });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void submitOrder(){
        loadingProgressDialog.show();
        SubmitInfo submitInfo = new SubmitInfo()
                .setYingqId(selectFloor.getValue())
                .setLouy(floor.getId())
                .setFloor(Integer.parseInt(etFloor.getText().toString()))
                .setRoom(etRoomNo.getText().toString())
                .setProblem(etContent.getText().toString())
                .setShangmsd(tvTimeSpace.getText().toString())
                .setLianxr(etName.getText().toString())
                .setLianxdh(etPhone.getText().toString())
                .setPicture(String.join(",",images));

        BaseRequest.getInstance().getApiServise().submit(submitInfo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(mContext) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        loadingProgressDialog.hide();
                    }

                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        LogUtils.e("******" + baseReponse);
                        ToastUtils.showToast("创建成功，稍后将有工作人员联系您");
                        finish();
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {
                    }
                });
    }

    private void initAddressPickerView() {
        // 设置CenterDecoration
        decoration = new DefaultCenterDecoration(this);
        decoration
                .setLineColor(Color.parseColor("#dd199475"))
//                .setDrawable(Color.parseColor("#199475"))
                //.setDrawable(Color.parseColor("#999999"))
                .setLineWidth(1)
                .setMargin(Util.dip2px(this, 10), Util.dip2px(this, -3), Util.dip2px(this, 10),
                        Util.dip2px(this, -3));
        mPicker =
                new OptionPicker.Builder(this, 2, this)
                        .dialog(new PickerDialog())
                        .setInterceptor(new BasePicker.Interceptor() {
                            @Override
                            public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                                int level = (int) pickerView.getTag();
                                pickerView.setVisibleItemCount(3);
                                // setInterceptor 可以根据level区分设置pickerview属性
                                pickerView.setCenterDecoration(decoration);
                                pickerView.setTextSize(15, 20);
                                pickerView.setColor(Color.parseColor("#199475"), Color.parseColor("#444444"));
                            }
                        }).create();
        PickerDialog pickerDialog = (PickerDialog) mPicker.dialog();
        Dialog dialog = pickerDialog.getDialog();

        //DefaultPickerDialog dialog = (DefaultPickerDialog) mPicker.dialog();
        pickerDialog.getTitleView().setText("请选择营区房间");
        // 设置弹窗
        dialog.setCanceledOnTouchOutside(true);
        dialog.getWindow().setGravity(Gravity.BOTTOM);

        // 拦截缺点按钮的事件
        pickerDialog.setOnPickerChooseListener(new OnPickerChooseListener() {
            @Override
            public boolean onConfirm() {
                selectFloor= subCampList.get(mPicker.getSelectedPosition()[0]);
                floor = selectFloor.getFloors().get(mPicker.getSelectedPosition()[1]);
                tvAddress.setText(selectFloor.getTitle() + " " + floor.getName());
                dialog.dismiss();
                // 返回false表示拦截
                return false;
            }

            @Override
            public void onCancel() {
            }
        });

        mPicker.setData(subCampList);
        getAddressData();
    }

    private void getAddressData() {
        BaseRequest.getInstance().getApiServise().getSubCampList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<List> baseReponse) {
                        List result = baseReponse.getResults();
                        List<SubCamp_Floor> list = GsonUtil.mapListToBeanList(result, SubCamp_Floor.class);
                        subCampList.clear();
                        subCampList.addAll(list);
                        getFloorData(0);
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) { }
                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception { }
                });
    }

    private void getFloorData(int position) {
        BaseRequest.getInstance().getApiServise().getSubCampFloorList(subCampList.get(position).getValue())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        Map result = baseReponse.getResults();
                        List<Floor> list = GsonUtil.mapListToBeanList((List) Objects.requireNonNull(result.get("records")), Floor.class);
                        subCampList.get(position).setFloors(list);
                        if (position!=subCampList.size()-1){
                            getFloorData(position+1);
                        }else {
                            mPicker.setData(subCampList);
                        }
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) { }
                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception { }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SimpleRxGalleryFinal.get().onActivityResult(requestCode, resultCode, data);
        if (requestCode == RxGalleryFinalApi.TAKE_IMAGE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            imageInfos.add(new ImageInfo().setImageUrl(RxGalleryFinalApi.fileImagePath.getPath()).setImageType(RecordedActivity.RESULT_TYPE_PHOTO));
            adapter.notifyDataSetChanged();
            isCompleteUpload = false;
        } else if (resultCode == RESULT_OK && data != null) {
            if (requestCode == 1) {
//                textureView.setVisibility(View.GONE);
//                iv_photo.setVisibility(View.GONE);
                int dataType = data.getIntExtra(RecordedActivity.INTENT_DATA_TYPE, RecordedActivity.RESULT_TYPE_VIDEO);
                if (dataType == RecordedActivity.RESULT_TYPE_VIDEO) {
                    String videoPath = data.getStringExtra(RecordedActivity.INTENT_PATH);
//                    tv_path.setText("视频地址: "+videoPath);
//                    textureView.setVisibility(View.VISIBLE);
//                    playVideo(videoPath);
                    imageInfos.add(new ImageInfo().setImageUrl(videoPath).setImageType(RecordedActivity.RESULT_TYPE_VIDEO));
                } else if (dataType == RecordedActivity.RESULT_TYPE_PHOTO) {
                    String photoPath = data.getStringExtra(RecordedActivity.INTENT_PATH);
//                    tv_path.setText("图片地址: "+photoPath);
//                    iv_photo.setVisibility(View.VISIBLE);
//                    iv_photo.setImageBitmap(BitmapFactory.decodeFile(photoPath));
                    imageInfos.add(new ImageInfo().setImageUrl(photoPath).setImageType(RecordedActivity.RESULT_TYPE_PHOTO));
                }
                isCompleteUpload = false;
                if (!isUploading){
                    currentPosition = imageInfos.size()-1;
                    uploadImage();
                }

                adapter.notifyDataSetChanged();
            }
        }
    }

    @OnClick({R.id.img_camera, R.id.img_album})
    public void onViewClicked(View view) {
        AndPermission.with(AppearActivity.this).permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .requestCode(0).callback(new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                switch (view.getId()) {
                    case R.id.img_camera:
                        RxGalleryFinalApi.openZKCamera(AppearActivity.this);
                        break;
                    case R.id.img_album:
                        openMulti();
                        break;
                }
            }

            @Override
            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            }
        }).start();
    }


    private void openMulti() {
//        RxGalleryFinal.with(this).hidePreview();
        RxGalleryFinal rxGalleryFinal = RxGalleryFinal
                .with(this)
                .image().maxSize(9)
                .multiple();
        if (mediaBeans != null && !mediaBeans.isEmpty()) {
            rxGalleryFinal
                    .selected(mediaBeans);
        }
        rxGalleryFinal
                .imageLoader(ImageLoaderType.FRESCO)
                .subscribe(new RxBusResultDisposable<ImageMultipleResultEvent>() {

                    @Override
                    protected void onEvent(ImageMultipleResultEvent imageMultipleResultEvent) throws Exception {
                        mediaBeans = imageMultipleResultEvent.getResult();
                        Toast.makeText(getBaseContext(), "已选择" + imageMultipleResultEvent.getResult().size() + "张图片", Toast.LENGTH_SHORT).show();
                        imageInfos.clear();
                        for (MediaBean mediaBean : mediaBeans) {
                            imageInfos.add(new ImageInfo().setImageUrl(mediaBean.getOriginalPath()).setImageType(RecordedActivity.RESULT_TYPE_PHOTO));
                        }
                        isCompleteUpload = false;
                        if (!isUploading){
                            currentPosition = currentPosition==0?0:imageInfos.size()-1;
                            uploadImage();
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        Toast.makeText(getBaseContext(), "OVER", Toast.LENGTH_SHORT).show();
                    }
                })
                .openGallery();
    }


    @OnClick(R.id.tv_time_space)
    public void onViewClicked() {
        try {
            // 设置选中时间
            Date date = sSimpleDateFormat.parse(tvTimeSpace.getText().toString());
            mTimePicker1.setSelectedDate(date.getTime());
        } catch (ParseException e) {
            // 如果没有设置选中时间，则取起始时间
            e.printStackTrace();
            mTimePicker1.setSelectedDate(new Date().getTime());
        }
        mTimePicker1.show();
    }

    @Override
    public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {

    }

    @OnClick(R.id.tv_address)
    public void onAddressClicked() {
        mPicker.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @OnClick(R.id.tv_submit)
    public void onSubmitClicked() {

        if (selectFloor==null){
            ToastUtils.showToast("请选择营区");
            return;
        }
        if (TextUtils.isEmpty(etFloor.getText().toString())){
            ToastUtils.showToast("请输入楼层");
            return;
        }
        if (TextUtils.isEmpty(etRoomNo.getText().toString())){
            ToastUtils.showToast("请输入房间号");
            return;
        }
//        if (TextUtils.isEmpty(tvTimeSpace.getText().toString())){
//            ToastUtils.showToast("请选择上门时间");
//            return;
//        }
        if (TextUtils.isEmpty(etContent.getText().toString())){
            ToastUtils.showToast("请输入相关描述");
            return;
        }
        if (TextUtils.isEmpty(etName.getText().toString())){
            ToastUtils.showToast("请输入联系人");
            return;
        }
        if (TextUtils.isEmpty(etPhone.getText().toString())){
            ToastUtils.showToast("请输入联系方式");
            return;
        }
        if(isCompleteUpload||imageInfos.size()==0){
            submitOrder();
        }
    }
}

//打开视频录制
//        findViewById(R.id.img_camera).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                AndPermission.with(AppearActivity.this).permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                        .requestCode(0).callback(new PermissionListener() {
//                    @Override
//                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
//                        Intent intent = new Intent(AppearActivity.this, RecordedActivity.class);
//                        startActivityForResult(intent, 1);
//                    }
//
//                    @Override
//                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
//                    }
//                }).start();
//            }
//        });
